<template>
  <div v-loading.lock="fullscreenLoading">
    <div class="zset-header">
        <el-input v-model="zsetInfo.key" size="small" :placeholder="$t('RedisOperating.PleaseEnterTheKey')">
            <template slot="prepend">zset</template>
            <el-button slot="append" icon="el-icon-check" @click="reNameKey"></el-button>
        </el-input>
        <el-input v-model="zsetInfo.ttl" size="small">
            <template slot="prepend">TTL</template>
            <el-button slot="append" icon="el-icon-check" @click="setExpired"></el-button>
        </el-input>
        <el-button type="success" icon="el-icon-refresh" circle @click="refresh"></el-button>
        <el-button type="danger" icon="el-icon-delete" circle @click="delKey"></el-button>
    </div>
    <div class="zset-addNewLine">
        <el-button type="primary" size="small" @click="addNewLineVisible=true">{{$t('RedisOperating.addNewLine')}}</el-button>
    </div>
    <div class="zset-value">
        <el-table :data="dataTable" border style="width: 100%">
            <el-table-column  type="index" label="id" width="180px"></el-table-column>
            <el-table-column  label="score" prop="score"></el-table-column>
            <el-table-column  label="member" prop="member"></el-table-column>
            <el-table-column>
                <template slot="header" slot-scope="scope">
                     <el-input v-model="searchTxt" size="mini" :title="disablePrompt" :placeholder="$t('homeVue.PleaseEnterKeyWords')" :disabled="disableSearch"/>
                </template>
                <template slot-scope="scope">
                    <el-button type="warning" icon="el-icon-edit" circle @click="editLineVisible=true;editRow=scope;editZset.score=scope.row.score;editZset.member=scope.row.member" size="small"></el-button>
                    <el-button type="danger" icon="el-icon-delete" circle @click="delSetRow(scope)" size="small"></el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="zset-page">
        <el-pagination
            background
            layout="prev, pager, next"
            :page-count="zsetInfo.total"
            @current-change="pagination">
        </el-pagination>
    </div>
    <el-dialog :title="$t('RedisOperating.addNewLine')" :visible.sync="addNewLineVisible" width="30%">
        <p>score：</p>
        <p><el-input  :placeholder="$t('RedisOperating.PleaseEnterScore')" v-model="addZset.score" clearable></el-input></p>
        <p>member：</p>
        <p><el-input  :placeholder="$t('RedisOperating.PleaseEnterMamber')"  v-model="addZset.member"  clearable></el-input></p>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addNewLine">{{$t('FormPlaceholder.OK')}}</el-button>
            <el-button @click="addNewLineVisible = false">{{$t('FormPlaceholder.cancel')}}</el-button>
        </span>
    </el-dialog>
     <el-dialog :title="$t('RedisOperating.editLine')" :visible.sync="editLineVisible" width="30%">
       <p>score：</p>
        <p><el-input  :placeholder="$t('RedisOperating.PleaseEnterScore')"  v-model="editZset.score" clearable></el-input></p>
        <p>member：</p>
        <p><el-input  :placeholder="$t('RedisOperating.PleaseEnterMamber')"  v-model="editZset.member"  clearable></el-input></p>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="editSetRow">{{$t('FormPlaceholder.OK')}}</el-button>
            <el-button @click="editLineVisible = false">{{$t('FormPlaceholder.cancel')}}</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import storage from '../../redis/storage'
export default {
    props:['tab'],
    data(){
        return {
            fullscreenLoading:true,
            tempKey:this.tab.key,
            addZset:{
                score:'',
                member:''
            },
            editZset:{
                score:'',
                member:''
            },
            editRow:{},
            addNewLineVisible:false,
            editLineVisible:false,
            disableSearch:true,
            disablePrompt:this.$t('RedisOperating.DataLoadingTips'),
            searchTxt:'',
            zsetInfo:{
                key:this.tab.key===undefined?"":this.tab.key,
                ttl:-1,
                size:100,
                index:1,
                total:0,
                data:[],
            }
        }
    },
    created(){
        this.refresh();
    },
    methods:{
        reNameKey(){
            if(this.tempKey&&this.tempKey!==this.zsetInfo.key){
                let client=storage.get('client')[this.tab.serverIdx]
                client.existsAsync(this.zsetInfo.key).then(res=>{
                    if(res===0){
                        client.renameAsync(this.tempKey,this.zsetInfo.key).then(res=>{
                            if(res==='OK'){
                                this.tempKey=this.zsetInfo.key
                                this.$emit('updateKeyName',storage.get('item')[this.tab.serverIdx],this.tab,this.zsetInfo.key)
                                this.$message({
                                    type:'success',
                                    message:this.$t('RedisOperating.ReNameSuccess')
                                })
                            }
                        })
                    }else{
                        this.zsetInfo.key=this.tempKey
                        this.$message({
                            type:"warning",
                            message:this.$t('RedisOperating.keyExists')
                        })
                    }
                })
            }
        },
        setExpired(){
            if(this.tempKey){
                let client=storage.get('client')[this.tab.serverIdx]
                client.expireAsync(this.tempKey,this.zsetInfo.ttl).then(res=>{
                    if(res===1){
                        this.$message({
                            type:'success',
                            message:this.$t('RedisOperating.ExpirationTimeSetSuccessfully')
                        })
                    }
                })
            }
        },
        refresh(){
            if(this.tempKey){
                this.disableSearch=true
                this.zsetInfo.key=this.tempKey
                this.disablePrompt=this.$t('RedisOperating.DataLoadingTips')
                let client=storage.get('client')[this.tab.serverIdx]
                client.ttlAsync(this.tempKey).then(res=>{
                    if(res===-2&&this.tempKey){
                        this.tempKey=''
                    }
                    this.zsetInfo.ttl=(res===-2?0:res);
                })
                this.zsetInfo.data=[];
                this.zrange(client)
            }else{
                this.fullscreenLoading=false;
            }
        },
        delKey(){
            let client=storage.get('client')[this.tab.serverIdx]
            this.$confirm(this.$t('homeVue.ConfirmDeletion'), this.$t('homeVue.prompt'), {
                confirmButtonText: this.$t('FormPlaceholder.OK'),
                cancelButtonText: this.$t('FormPlaceholder.cancel'),
                type: 'warning'
            }).then(() => {
              client.delAsync(this.tempKey).then(res=>{
                  if(res===1){
                      this.$message({
                        type:'success',
                        message:this.$t("RedisOperating.DeletedSuccessfully")
                      })
                      this.$emit('removeTab',this.tab.name)
                      this.$emit('delKey',storage.get('item')[this.tab.serverIdx],this.tab.index)
                  }
              })
            }).catch(() => {});
        },
        addNewLine(){
            if(this.zsetInfo.key&&this.addZset.score&&this.addZset.member){
                let client=storage.get('client')[this.tab.serverIdx]
                client.existsAsync(this.zsetInfo.key).then(res=>{
                     if(res===1&&!this.tempKey){
                        this.$message({
                            type:"warning",
                            message:this.$t('RedisOperating.keyExists')
                        })
                    }else{
                        if(this.tempKey){
                            this.zsetInfo.key=this.tempKey
                        }
                        client.zaddAsync(this.zsetInfo.key,this.addZset.score,this.addZset.member).then(res=>{
                            if(res===1){
                                this.$message({
                                    type:'success',
                                    message:this.$t('RedisOperating.addSuccess')
                                })
                                this.zsetInfo.data.push({"score":this.addZset.score,"member":this.addZset.member})
                                this.addZset.score='';
                                this.addZset.member='';
                                this.addNewLineVisible=false;
                                if(!this.tempKey){
                                    this.$emit('addSuccessCall',this.zsetInfo.key,this.tab)
                                }
                            }else if(res===0){
                                this.$message({
                                    type:'warning',
                                    message:this.$t('RedisOperating.AlreadyExistsZset')
                                })
                            }
                        }).catch(e=>{
                            this.$message({
                                type:'error',
                                message: e.message
                            })
                        })
                    }
                })
            }else{
                this.$message({
                    type:"warning",
                    message:this.$t('RedisOperating.keyScoreMemberCannotBeEmpty')
                })
            }
        },
        zrange(client){
            client.zrangeAsync([this.tempKey, 0, -1, 'WITHSCORES']).then((reply) => {
                const zsetData = [];
                const { length } = reply;
                for (let i = 0; i < (length - 1); i++) {
                    if (!(i % 2)) {
                        zsetData.push({ member: reply[i], score: reply[i + 1] });
                    }
                }
                this.zsetInfo.data = zsetData;
                this.disableSearch=false;
                this.disablePrompt='';
                this.fullscreenLoading=false;
            });
        },
        pagination(v){
            this.zsetInfo.index=v;
        },
        editSetRow(){
            let client=storage.get('client')[this.tab.serverIdx]
            let index=((this.zsetInfo.index-1)*this.zsetInfo.size)+this.editRow.$index;
            client.zremAsync(this.tempKey,this.editRow.row.member).then(res=>{
                if(res === 1){
                    client.zaddAsync(this.tempKey,this.editZset.score,this.editZset.member).then(res=>{
                        if(res === 1){
                            this.$set(this.zsetInfo.data,index,{"score":this.editZset.score,"member":this.editZset.member})
                            this.editRow={};
                            this.editZset.score='';
                            this.editZset.member='';
                            this.editLineVisible=false;
                        }else{
                            this.$message({
                                type:'error',
                                message:this.$t('RedisOperating.addNewLineError')
                            })
                        }
                    })
                }else{
                    this.$message({
                        type:'error',
                        message:this.$t('RedisOperating.rowRemError')
                    })
                }
            })
        },
        delSetRow(row){
            let client=storage.get('client')[this.tab.serverIdx]
            this.$confirm(this.$t('homeVue.ConfirmDeletion'), this.$t('homeVue.prompt'), {
                confirmButtonText: this.$t('FormPlaceholder.OK'),
                cancelButtonText: this.$t('FormPlaceholder.cancel'),
                type: 'warning'
            }).then(() => {
              client.zremAsync(this.tempKey,row.row.member).then(res=>{
                  let index=((this.zsetInfo.index-1)*this.zsetInfo.size)+row.$index
                  this.zsetInfo.data.splice(index, 1);
                  if(res === 1){
                      this.$message({
                          type:'success',
                          message:this.$t('RedisOperating.DeletedSuccessfully')
                      })
                      //列表如果没有数据了则代表此key应该被删除
                      if(this.zsetInfo.data.length===0){
                        this.$emit('removeTab',this.tab.name)
                        this.$emit('delKey',storage.get('item')[this.tab.serverIdx],this.tab.index)
                      }
                  }
              })
            }).catch(() => {});
        }
    },
    computed:{
        dataTable:function(){
            const start = (this.zsetInfo.index - 1) * this.zsetInfo.size;
            const data=this.dataAfterFilter.slice(start,start+this.zsetInfo.size);
            this.zsetInfo.total=Math.ceil(this.dataAfterFilter.length/this.zsetInfo.size)
            if((this.zsetInfo.index>this.zsetInfo.total)&&this.zsetInfo.total!=0){
                this.zsetInfo.index=this.zsetInfo.total;
            }else if((this.zsetInfo.index>this.zsetInfo.total)&&this.zsetInfo.total===0){
                this.zsetInfo.index=1;
            }
            return data;
        },
        dataAfterFilter() {
            if(!this.searchTxt){
                return this.zsetInfo.data;
            }
            return this.zsetInfo.data.filter(line => line["member"].toLowerCase().includes(this.searchTxt.toLowerCase()));
        }
    }
}
</script>

<style scoped>
.zset-header .el-input{
    width: 30%;
}
.zset-header .el-button+.el-button{
    margin: 0px;
}
.zset-header .el-button.is-circle{
    padding: 6px;
    margin: 0px 5px;
}
.zset-addNewLine{
    margin: 10px 0px;
}
.zset-page{
    margin-top: 15px;
    text-align: center;
}
</style>